package com.sydsen.imager.painter;

import com.sydsen.imager.Canvas;
import com.sydsen.imager.elements.Text;
import com.sydsen.imager.util.FontUtil;

import java.awt.font.TextAttribute;
import java.text.AttributedString;

/**
 * @Auther: syh
 * @Date: 2021/11/1
 * @Description:
 */
public class TextPainter extends AbstractPainter<Text> {

    @Override
    protected void doDraw(Canvas canvas, Text text) throws Exception {
        //设置字体、颜色
        canvas.getGraphics().setFont(text.font());
        canvas.getGraphics().setColor(text.color());

        //带删除线样式的文字要特殊处理
        if (text.rich()) {
            AttributedString as = new AttributedString(text.text());
            as.addAttribute(TextAttribute.FONT, text.font());
            if (text.strikeThrough()) {
                as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, 0, text.text().length());
            }
            if (text.underline()) {
                as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, 0, text.text().length());
            }
            if (text.oblique()) {
                // 斜体
                as.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, 0, text.text().length());
            }
            canvas.getGraphics().drawString(as.getIterator(), text.x(), text.y());
        } else {
            canvas.getGraphics().drawString(text.text(), text.x() , text.y());
        }
    }

    @Override
    protected int getElementHeight(Text element) {
        return (element.lines()  - element.lineNumber()) * element.font().getSize() * 2;
    }

    @Override
    protected int getElementWidth(Text element) {
        return FontUtil.getTextWidth(element.text(), element.font());
    }
}
